﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Mail;
using System.Text;

namespace PageAdmin.Utils
{
    /// <summary>
    /// 邮件发送帮助类
    /// </summary>
    public class EmailHelper
    {
        /// <summary>
        /// 发送邮件,发送生成则返回success,否则会发错误信息,System.Net.Mail不支持ssl
        /// </summary>
        /// <param name="emailSetting">邮件参数设置类</param>
        /// <param name="mailTo">邮箱号码</param>
        /// <param name="mailSubject">邮件标题</param>
        /// <param name="mailBody">邮件内容</param>
        /// <param name="mailReply">邮件回复</param>
        /// <param name="mailCC">邮件抄送</param>
        /// <param name="attachments">附件</param>
        /// <returns></returns>
        public static TipsInfo Send(EmailSetting emailSetting, string mailTo, string mailSubject, string mailBody, string mailReply = null, string mailCC = null, IEnumerable<string> attachments = null)
        {
            bool enableSsl = emailSetting.EnableSsl;
            if(enableSsl)
            {
                return SendSSL(emailSetting, mailTo, mailSubject, mailBody, mailReply, mailCC, attachments);
            }
            TipsInfo tipsInfo = new TipsInfo()
            {
                State = 0,
                Msg = ""
            };
            string userName = emailSetting.UserName;
            string passWord = emailSetting.PassWord;
            string displayName = emailSetting.DisplayName;
            string host = emailSetting.Host;
            int port = emailSetting.Port;
            if (!StringHelper.IsEmail(userName) || string.IsNullOrEmpty(passWord) || string.IsNullOrEmpty(host))
            {
                tipsInfo.Msg = "邮件参数未配置正确！";
                return tipsInfo;
            }
            if (string.IsNullOrEmpty(mailTo))
            {
                tipsInfo.Msg = "收件邮箱未设置！";
                return tipsInfo;
            }
            if (string.IsNullOrEmpty(mailSubject))
            {
                tipsInfo.Msg = "邮件主题不能为空！";
                return tipsInfo;
            }
            //System.Net.ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(RemoteServerCertificateValidationCallback);
            SmtpClient smtp = new SmtpClient(host, port);
            smtp.DeliveryMethod = SmtpDeliveryMethod.Network;//指定电子邮件发送方式
            smtp.Credentials = new NetworkCredential(userName, passWord);
            smtp.EnableSsl = enableSsl;
            //smtp.UseDefaultCredentials =true;
            Encoding encoding = Encoding.UTF8;
            MailAddress mailtFrom= new MailAddress(userName, displayName, encoding);
            MailAddress mailto=new MailAddress(mailTo, "", encoding);
            MailMessage mailMessage = new MailMessage(mailtFrom, mailto);
            if (attachments != null)
            {
                foreach (string attachment in attachments)
                {
                    mailMessage.Attachments.Add(new Attachment(IOHelper.MapPath(attachment)));
                }
            }
            if (!string.IsNullOrEmpty(mailReply))
            {
                mailMessage.ReplyToList.Add(mailReply);
            }
            if (!string.IsNullOrEmpty(mailCC))
            {
                mailMessage.CC.Add(mailCC);
            }
            mailMessage.Subject = mailSubject;
            mailMessage.Body = mailBody;
            mailMessage.IsBodyHtml = true;
            mailMessage.SubjectEncoding = encoding;
            mailMessage.BodyEncoding = encoding;
            mailMessage.HeadersEncoding = encoding;
            mailMessage.Priority = MailPriority.Normal;
            try
            {
                smtp.Send(mailMessage);
                tipsInfo.Msg = "success";
                tipsInfo.State = 1;
            }
            catch (Exception e)
            {
                tipsInfo.Msg = e.Message;
            }
            finally
            {
                smtp.Dispose();
            }

            return tipsInfo;
        }

        /// <summary>
        /// 发送邮件,发送生成则返回success,否则会发错误信息,System.Net.Mail不支持ssl
        /// </summary>
        /// <param name="emailSetting"></param>
        /// <returns></returns>
        public static TipsInfo Send(EmailSetting emailSetting)
        {
            return Send(emailSetting, emailSetting.MailTo, emailSetting.MailSubject, emailSetting.MailBody, emailSetting.MailReply, emailSetting.MailCC, emailSetting.Attachments);
        }

        private static TipsInfo SendSSL(EmailSetting emailSetting, string mailTo, string mailSubject, string mailBody, string mailReply = null, string mailCC = null, IEnumerable<string> attachments = null)
        {
            TipsInfo tipsInfo = new TipsInfo()
            {
                State = 0,
                Msg = ""
            };
            System.Web.Mail.MailMessage mail = new System.Web.Mail.MailMessage();
            if (attachments != null)
            {
                foreach (string attachment in attachments)
                {
                    mail.Attachments.Add(new System.Web.Mail.MailAttachment(IOHelper.MapPath(attachment)));
                }
            }
            try
            {
                mail.To = mailTo;
                mail.From =$"{emailSetting.DisplayName}<{emailSetting.UserName}>";
                mail.Subject = mailSubject;
                mail.BodyFormat = System.Web.Mail.MailFormat.Html;
                mail.Body = mailBody;
                mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); //basic authentication

                mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", emailSetting.UserName); //set your username here

                mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", emailSetting.PassWord); //set your password here

                mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", emailSetting.Port);//set port

                mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");//set is ssl

                System.Web.Mail.SmtpMail.SmtpServer = emailSetting.Host;
                System.Web.Mail.SmtpMail.Send(mail);
                tipsInfo.Msg = "success";
                tipsInfo.State = 1;
            }
            catch (Exception e)
            {
                tipsInfo.Msg = e.Message;
            }
            return tipsInfo;

        }

        private static bool RemoteServerCertificateValidationCallback(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }


    }
}